/*
 * This servlet controls the login and logout of a user
 */
package controllers.classes;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Employee;
import models.Student;
import models.User;
import net.sf.cglib.proxy.Dispatcher;
import dao.EmployeeDao;
import classes.HibernateUtil;
import classes.Password;
import classes.Url;
import dao.ActivationDao;
import dao.StudentDao;
import dao.UserDao;
import models.Activation;
import org.hibernate.Session;

/**
 *
 * @author Achie
 */
@WebServlet(name = "LoginController", urlPatterns = {"/LoginController"})
public class LoginController extends HttpServlet {

    /*
     * This get method will log out the user
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        //set all the session attributes to null
        session.setAttribute("user", null);
        session.setAttribute("userdetails", null);
        session.setAttribute("userrole", null);
        response.sendRedirect(request.getContextPath());
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //------------------------------------------------------------------
        //This part checks whether the administrator panel is enabled or not.
        //------------------------------------------------------------------
        if (request.getParameter("isenabled") != null) {
            HttpSession session = request.getSession();
            if (request.getParameter("isenabled").equals("0")) { //if not enabled, it is a teacher
                session.setAttribute("userrole", "Teacher");
            } else if (request.getParameter("isenabled").equals("1")) { //if enabled, it is an administrator
                session.setAttribute("userrole", "Administrator");
            }
            response.sendRedirect(Url.getHistory()); //redirect to the previous page
            return;
        }

        //------------------------------------------------------------------
        //Get values from the login form
        //------------------------------------------------------------------
        String email = request.getParameter("email");
        String password = request.getParameter("password"); //hash the inserted password
        //------------------------------------------------------------------
        //Make hash password
        //------------------------------------------------------------------
        String hashedPassword = null;
        try {
            Password pass = new Password(password);
            hashedPassword = pass.getHashedPassword(); //get the hashed password
        } catch (Exception e) {
        }
        //------------------------------------------------------------------
        //Get all members
        //------------------------------------------------------------------
        HibernateUtil hu = new HibernateUtil();
        Session sessie = hu.openSession();
        UserDao md = new UserDao(sessie);
        List<User> member_list = md.findAll();
        Activation a = new Activation();
        ActivationDao ad = new ActivationDao(sessie);
        List<Activation> adlist = ad.findAll(); //get activations

        for (int i = 0; i < member_list.size(); i++) { //loop through each member and look if the filled in email is available in the member list
            String tempEmail = member_list.get(i).getEmail();
            if (tempEmail.equals(email)) { //if true, the email does exist in the database
                if (member_list.get(i).getPassword().equals(hashedPassword)) { //if the inserted password is also equal, login member
                    for (int j = 0; j < adlist.size(); j++) {
                        if (adlist.get(j).isStudent().getId() == member_list.get(i).getMember_id()) {
                            if (!adlist.get(j).isActivated()) {
                                //doe error
                                loginFailed(request, response, "activaterror");
                                return;
                            }

                        }
                    }
                    HttpSession session = request.getSession(); //Make session
                    User member = member_list.get(i);
                    session.setAttribute("user", member); //set the user in the session

                    long member_id = member.getMember_id();

                    //Check if logged in as employee
                    EmployeeDao ed = new EmployeeDao(sessie);
                    // List<Employee> employers = ed.findAll();
                    if (ed.get(member_id) != null) { //Logged in as employee
                        Employee employer = ed.get(member_id);
                        session.setAttribute("userdetails", employer);
                        session.setAttribute("userrole", "Teacher");
                    } else { //ingelogd als student

                        StudentDao sd = new StudentDao(sessie);
                        List<Student> studentenlijst = sd.findAll(); //get all studentslist
                        Student student = sd.get(member_id);

                        session.setAttribute("userdetails", student);//set in session
                        session.setAttribute("userrole", "Student");
                    }
                    
                    response.sendRedirect(Url.getHistory()); //redirect to the previous page
                    return;
                } else { //password is incorrent
                    loginFailed(request, response, "invalidpas");
                    return;
                }
            }
        }

        //------------------------------------------------------------------
        //The following is only visible if the inserted email was not found in the database
        //------------------------------------------------------------------
        loginFailed(request, response, "Login credentials incorrect! Please try again.");
        return;
    }

    /*
     * This method is executes if the login has failed
     */
    public void loginFailed(HttpServletRequest request, HttpServletResponse response, String errorMessage) throws IOException, ServletException {

        HttpSession s = request.getSession();
        if (errorMessage.equals("activaterror")) {
            s.setAttribute("activation_false", "true"); //trigger the activation error
        }
        if (errorMessage.equals("invalidpas")) {
            s.setAttribute("login_fail", "true"); //set the attribute
        }

        String redirurl = request.getParameter("redir");

        response.sendRedirect(redirurl);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
